import { app, shell, BrowserWindow, ipcMain, Tray, Menu,dialog } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

let childWindow
function newWindow(mainWindow, args) {
  if (!mainWindow){return}
  if (!args){return}
  let path = ''
  let width = 670
  let height = 400
  if (args.length > 0){
    path = args[0]
    if (args.length > 1){
      width = args[1]
    }
    if (args.length > 2){
      height = args[2]
    }
  }

  // Create the browser window.A
  childWindow = new BrowserWindow({
    width: width,
    height: height,
    show: false,
    parent: mainWindow,
    // transparent: true, // 设置窗口背景透明
    frame: false, // 隐藏窗口边框
    icon: join(__dirname,'../../resources/icon.ico'),
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
    },
  })
  //开启开发工具DevTools
  // childWindow.webContents.openDevTools();

  childWindow.on('ready-to-show', () => {
    childWindow.show()
  })

  childWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    childWindow.loadURL(process.env['ELECTRON_RENDERER_URL'] + '#' + path)
  } else {
    childWindow.loadFile(join(__dirname, '../renderer/index.html#' + path))
  }
  //置顶监听
  ipcMain.on('top_child', () => {
    childWindow.setAlwaysOnTop(true)
  })
  //置顶监听
  ipcMain.on('cancle_top_child', () => {
    childWindow.setAlwaysOnTop(false)
  })
  //最小化监听
  ipcMain.on('min_child', () => {
    childWindow.minimize()
  })
  //大窗口化监听
  ipcMain.on('max_child', () => {
    childWindow.maximize()
  })
  //小窗口化监听
  ipcMain.on('cancel_max_child', () => {
    childWindow.unmaximize()
  })
  //关闭监听
  ipcMain.on('hide_child', () => {
    // 使窗口不显示在任务栏中
    childWindow.hide()
  })
  //关闭监听
  ipcMain.on('destroy_child', () => {
    childWindow.destroy();
  })

}

export default newWindow
